package com.cloudcentral.controller;

import com.cloudcentral.entity.dto.SMSCodeDTO;
import com.cloudcentral.exception.FailureException;
import com.cloudcentral.util.PatternUtils;
import com.cloudcentral.util.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;

/**
 * Create by Administrator
 * 2023/10/31 9:37
 */
@Slf4j
@RestController
@RequestMapping("/sms")
@Tag(name = "短信相关")
public class SMSController extends BaseController {
  private final RedissonClient redissonClient;

  @Autowired
  public SMSController(RedissonClient redissonClient) {
    this.redissonClient = redissonClient;
  }

  @PostMapping("/code")
  @Operation(summary = "短信验证码", description = "默认: 666666")
  public Result<Long> send(SMSCodeDTO dto) throws FailureException {
    if (StringUtils.isBlank(dto.getPhone())) throw new FailureException("缺少手机号码");
    else if (!PatternUtils.isPhone(dto.getPhone())) throw new FailureException("手机号格式错误");
    else {
      RBucket<String> bucket = redissonClient.getBucket(dto.getPhone());
      if (StringUtils.isNotBlank(bucket.get())) throw new FailureException("发送验证码冷却中");
      else {
        // 生成验证码
        // String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        Duration duration = Duration.ofMinutes(1);
        bucket.set("666666", duration);
        return Result.ok(duration.getSeconds());
      }
    }
  }
}
